package net.gaox.search.sender.kafka;

import com.alibaba.fastjson.JSON;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.gaox.search.conf.KafkaConfig;
import net.gaox.search.mysql.dto.MySqlRowData;
import net.gaox.search.sender.ISender;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * <p> 增量数据kafka投递 </p>
 *
 * @author gaox·Eric
 * @site gaox.net
 * @date 2019/12/20 16:18
 */
@Slf4j
@Component("kafkaSender")
@RequiredArgsConstructor
public class KafkaSender implements ISender {

    private final KafkaConfig kafkaConfig;
    private final KafkaTemplate<String, String> kafkaTemplate;

    @Override
    public void sender(MySqlRowData rowData) {
        kafkaTemplate.send(kafkaConfig.getTopic(), JSON.toJSONString(rowData));
    }

    @KafkaListener(topics = "#{kafkaConfig.topic}", groupId = "ad-search")
    public void processMysqlRowData(ConsumerRecord<?, ?> record) {

        Optional<?> kafkaMessage = Optional.ofNullable(record.value());
        if (kafkaMessage.isPresent()) {
            Object message = kafkaMessage.get();
            MySqlRowData rowData = JSON.parseObject(message.toString(), MySqlRowData.class);
            log.info("kafka processMysqlRowData: {}", JSON.toJSONString(rowData));
        }
    }

}
